package koscom.corebase.nam;
import java.awt.Color;
import java.awt.Component;
import java.awt.EventQueue;
import java.awt.Font;
import java.awt.Insets;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.nio.ByteBuffer;
import java.text.NumberFormat;
import java.text.ParseException;
import java.util.Enumeration;

import javax.swing.DefaultComboBoxModel;
import javax.swing.JButton;
import javax.swing.JComboBox;
import javax.swing.JFormattedTextField;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JPasswordField;
import javax.swing.JScrollPane;
import javax.swing.JSeparator;
import javax.swing.JTable;
import javax.swing.JTextField;
import javax.swing.ListSelectionModel;
import javax.swing.UIDefaults;
import javax.swing.UIManager;
import javax.swing.border.EmptyBorder;
import javax.swing.table.DefaultTableCellRenderer;
import javax.swing.table.DefaultTableModel;
import javax.swing.table.TableCellRenderer;
import javax.swing.table.TableColumn;
import javax.swing.text.MaskFormatter;
import javax.swing.text.NumberFormatter;

import java.awt.event.FocusAdapter;
import java.awt.event.FocusEvent;


@SuppressWarnings("serial")
public class A2002 extends JFrame {
	
	private JPanel contentPane;
	private JFormattedTextField txtAccNum;
	private JTextField txtAccName;
	private JTable tblApryu;
	private JTextField txtResult;
	private DefaultTableModel model;
	private JPasswordField txtPassword;
	private JTextField txtArBranch;
	private JTextField txtArReason;
	private JTextField txtArDrid;
	private JFormattedTextField txtArAmount;
	JComboBox cmbArType;
	NumberFormatter numberFormatter;
	SClient client;
	JButton btnOK;
	int tableSelectedRow = -1;
	
	/**
	 * Launch the application.
	 */
	public static void main(String[] args) {
		//기본 폰트 설정
		try {
			UIDefaults swingComponentDefaultTable = UIManager.getDefaults();
			Enumeration<Object> allDefaultKey = swingComponentDefaultTable.keys();
			while(allDefaultKey.hasMoreElements()) {
				String defaultKey = allDefaultKey.nextElement().toString();
				if(defaultKey.indexOf("font") != -1) {
					Font newDefaultFont = new Font("맑은 고딕", Font.PLAIN, 12);
					//System.out.println(defaultKey);
					UIManager.put(defaultKey, newDefaultFont);
				}
			}
		UIManager.getDefaults().put("Button.margin", new Insets(0,0,0,0));
		} catch (Exception e) {
			e.printStackTrace();
		}		
		EventQueue.invokeLater(new Runnable() {
			public void run() {
				try {
					A2002 frame = new A2002();
					frame.setVisible(true);
					frame.txtAccNum.requestFocus();
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
		});
	}

	/**
	 * Create the frame.
	 */
	public A2002() {
		
		MaskFormatter mf1 = null;
		try {
			mf1 = new MaskFormatter("###-##-######");
			mf1.setPlaceholder("");
		} catch (ParseException e1) {
			e1.printStackTrace();
		}
		
		numberFormatter = new NumberFormatter( 
	            NumberFormat.getIntegerInstance());
		numberFormatter.setAllowsInvalid(false);  
	    numberFormatter.setCommitsOnValidEdit(true);
	    
	    client = new SClient(null, 0, false);
		
		client.setListener(new SClient.OnListener() {
			@Override
			public void onRcvData(ByteBuffer rcvBuff) {
				try {
					byte[] trid = new byte[6];
					rcvBuff.get(trid, 0, trid.length);
					String trString = new String(trid, "UTF-8");
					
					if(trString.equals("2222OO"))
					{
						System.out.println("2222OO");
						byte[] bytes = new byte[rcvBuff.remaining()];
						rcvBuff.get(bytes);
						String rString = new String(bytes, "UTF-8");
						txtAccName.setText(rString.substring(0,20).trim());
						model.setRowCount(0);
					}
					else if(trString.equals("2222XX"))
					{
						System.out.println("2222XX");
						txtResult.setText("해당 계좌가 존재하지 않습니다");
						//setEmpty(allComponents);
						txtAccName.setText("");
						txtPassword.setText("");
						model.setRowCount(0);
					}
					else if(trString.equals("2222PX"))
					{
						System.out.println("2222PX");
						txtResult.setText("비밀번호가 일치하지 않습니다");
						txtPassword.setText("");
						model.setRowCount(0);
					}
					else if(trString.equals("2222OW"))
					{
						System.out.println("2222OW");
						if(cmbArType.getSelectedIndex()==0)
						{
							txtResult.setText("등록할 압류내역을 입력하여 주십시오");
						}
						else
							txtResult.setText("해지할 압류내역을 선택하여 주십시오");
						model.setRowCount(0);
						txtArBranch.setText("");
						txtArReason.setText("");
						txtArDrid.setText("");
						txtArAmount.setValue(null);
						requestApryuList();
					}
					else if(trString.equals("20020A"))
					{
						txtResult.setText("이미 등록된 압류번호 입니다.");
					}
					else if(trString.equals("20021R") || trString.equals("20020R"))
					{
						if(trString.equals("20021R"))
						{
							txtResult.setText("해지가 완료되었습니다");
						}
						else
							txtResult.setText("등록이 완료되었습니다");
						model.setRowCount(0);
						txtArBranch.setText("");
						txtArReason.setText("");
						txtArDrid.setText("");
						txtArAmount.setValue(null);
						requestApryuList();
					}
					else if(trString.equals("20029E"))
					{
						if(cmbArType.getSelectedIndex()==1)
						{
							btnOK.setEnabled(false);
							txtResult.setText("압류 내역이 없습니다");
						}
						else if(cmbArType.getSelectedIndex()==0)
						{
							btnOK.setEnabled(true);
						}
					}
					else if(trString.equals("20029D"))
					{
						if(cmbArType.getSelectedIndex()==1)
						{
							btnOK.setEnabled(true);
						}
						else if(cmbArType.getSelectedIndex()==0)
						{
							btnOK.setEnabled(true);
						}
					}
					else if(trString.equals("200299"))
					{
						if(cmbArType.getSelectedIndex()==0)
							btnOK.setEnabled(false);
						else if(cmbArType.getSelectedIndex()==1)
							btnOK.setEnabled(true);
						//압류 내역 조회 - 테이블에 채우기.
						//System.out.println("압류내역 조회");
						//ar_date
						byte[] readByte = new byte[20];
						rcvBuff.get(readByte, 0, 19);
						String[] row = new String[11];
						row[0] = new String(readByte, "UTF-8").trim();
						
						//acc_num
						readByte = new byte[11];
						rcvBuff.get(readByte, 0, 11);
						row[1] = new String(readByte, "UTF-8").trim();
						
						//ar_id
						readByte = new byte[4];
						rcvBuff.get(readByte, 0, 4);
						row[7] = new String(readByte, "UTF-8").trim();
						
						//ar_check
						readByte = new byte[4];
						rcvBuff.get(readByte, 0, 4);
						row[8] = new String(readByte, "UTF-8").trim();
						
						//ar_dr_id
						readByte = new byte[20];
						rcvBuff.get(readByte, 0, 19);
						row[3] = new String(readByte, "UTF-8").trim();
						
						//ar_branch
						readByte = new byte[20];
						rcvBuff.get(readByte, 0, 19);
						row[2] = new String(readByte, "UTF-8").trim();
						
						//ar_amount
						readByte = new byte[20];
						rcvBuff.get(readByte, 0, 19);
						row[9] = new String(readByte, "UTF-8").trim();
						
						//ar_reason
						readByte = new byte[20];
						rcvBuff.get(readByte, 0, 19);
						row[10] = new String(readByte, "UTF-8").trim();
						
						//ar_cancle
						readByte = new byte[20];
						rcvBuff.get(readByte, 0, 19);
						row[5] = new String(readByte, "UTF-8").trim();
						
						//ar_cancle_date
						readByte = new byte[20];
						rcvBuff.get(readByte, 0, 19);
						row[6] = new String(readByte, "UTF-8").trim();
						
						row[4] = new String("압류(전거래정지)");
						model.addRow(row);
					}
					
				}catch(Exception e){ System.out.println("onRcv err"); e.printStackTrace(); }
			}
		});
	    
		setTitle("CoreBASE [2002] 계좌처분제한등록/해지");
		setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		setBounds(100, 100, 774, 485);
		contentPane = new JPanel();
		contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
		setContentPane(contentPane);
		contentPane.setLayout(null);
		
		JLabel lblNewLabel = new JLabel("처리구분");
		lblNewLabel.setBounds(12, 11, 90, 15);
		contentPane.add(lblNewLabel);
		
		JLabel lblNewLabel_1 = new JLabel("계좌번호");
		lblNewLabel_1.setBounds(12, 38, 90, 15);
		contentPane.add(lblNewLabel_1);
		
		JLabel lblNewLabel_2 = new JLabel("비밀번호");
		lblNewLabel_2.setBounds(370, 38, 90, 15);
		contentPane.add(lblNewLabel_2);
		
		txtAccNum = new JFormattedTextField(mf1);
		txtAccNum.addFocusListener(new FocusAdapter() {
			@Override
			public void focusLost(FocusEvent e) {
				findAccountName();
			}
		});
		txtAccNum.addKeyListener(new KeyAdapter() {
			@Override
			public void keyPressed(KeyEvent e) {
				if (e.getKeyCode() == KeyEvent.VK_ENTER) {
					findAccountName();
				}
			}
		});
		txtAccNum.setBounds(114, 35, 116, 21);
		txtAccNum.setDocument(new JTextFieldLimit(13));
		contentPane.add(txtAccNum);
		
		txtAccName = new JTextField();
		txtAccName.setFocusable(false);
		txtAccName.setEditable(false);
		txtAccName.setBounds(242, 35, 116, 21);
		contentPane.add(txtAccName);
		
		JButton btnSend = new JButton("전송");
		btnSend.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				getApryuListByAccPW();
			}
		});
		btnSend.setBounds(689, 34, 65, 23);
		contentPane.add(btnSend);
		
		JScrollPane scrollPane = new JScrollPane();
		scrollPane.setBounds(12, 150, 742, 248);
		contentPane.add(scrollPane);
		
		String header [] = {"압류등록일","계좌번호","압류등록자","압류등록번호","사고유형","압류해지자","압류해지일", 
				"seq번호", "ar_check", "ar_amount", "ar_reason"};
		model = new DefaultTableModel(null,header);
		tblApryu = new JTable(model){
			@Override
			public boolean isCellEditable(int row, int column) {
				return false;
			}
		};
		tblApryu.getTableHeader().setReorderingAllowed(false);
		tblApryu.getTableHeader().setResizingAllowed(false);
		tblApryu.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
		//테이블 순서변경금지, 리사이징 금지, 한줄만 선택 가능, 편집금지.
		
		for(int i=7; i<=10; i++)
		{
			TableColumn tblCol = tblApryu.getColumnModel().getColumn(i);
			tblCol.setMaxWidth(0);
			tblCol.setMinWidth(0);
			tblCol.setWidth(0);
			tblCol.setPreferredWidth(0);
		}
		
		tblApryu.addMouseListener(new MouseAdapter() {
			@Override
			public void mouseClicked(MouseEvent e) {
				if(cmbArType.getSelectedIndex()==1)
				{
					JTable tbl = (JTable)e.getSource();
					int row = tbl.getSelectedRow();
					System.out.println(tbl.getValueAt(row, 7));
					txtArBranch.setText((String)tbl.getValueAt(row, 2));
					txtArDrid.setText((String)tbl.getValueAt(row, 3));
					txtArAmount.setText((String)tbl.getValueAt(row, 9));
					txtArReason.setText((String)tbl.getValueAt(row, 10));
					tableSelectedRow = row;
				}
			}
		});
		tblApryu.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
			
		scrollPane.setViewportView(tblApryu);
		
		txtResult = new JTextField();
		txtResult.setEditable(false);
		txtResult.setBounds(12, 420, 742, 21);
		contentPane.add(txtResult);
		txtResult.setColumns(10);
		
		cmbArType = new JComboBox();
		cmbArType.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				btnOK.setEnabled(false);
				txtArBranch.setText("");
				txtArReason.setText("");
				txtArDrid.setText("");
				txtArAmount.setValue(null);
			}
		});
		cmbArType.setModel(new DefaultComboBoxModel(new String[] {"등록", "해지"}));
		cmbArType.setBounds(114, 7, 116, 23);
		contentPane.add(cmbArType);
		
		txtPassword = new JPasswordField();
		txtPassword.addKeyListener(new KeyAdapter() {
			@Override
			public void keyPressed(KeyEvent e) {
				if(e.getKeyChar() == KeyEvent.VK_ENTER)
				{
					getApryuListByAccPW();
				}
			}
		});
		txtPassword.setEchoChar('*');
		txtPassword.setBounds(472, 35, 60, 21);
		txtPassword.setDocument(new JTextFieldLimit(4));
		//txtJKSSN.setDocument(new JTextFieldLimit(13));
		
		contentPane.add(txtPassword);
		
		btnOK = new JButton("확인");
		btnOK.setEnabled(false);
		btnOK.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				/**
				 * 확인버튼 - 압류 등록/해지 
				 */
				ByteBuffer sendBuffer = ByteBuffer.allocateDirect(1024);
				sendBuffer.clear();
				switch(cmbArType.getSelectedIndex())
				{
				case 0:
					System.out.println("case 0 - 등록");
					if(txtArBranch.getText().isEmpty() || txtArDrid.getText().isEmpty() || txtArAmount.getText().isEmpty())
					{
						txtResult.setText("압류 등록처, 압류번호, 압류금액을 입력하여 주십시오");
						break;
					}
					//tr		06
					sendBuffer.position(0);
					sendBuffer.limit(6);
					sendBuffer.put("20020S".getBytes());
					
					//계좌		11	6~17
					sendBuffer.position(sendBuffer.limit());
					sendBuffer.limit(sendBuffer.limit()+11);
					sendBuffer.put(txtAccNum.getText().replaceAll("-", "").getBytes());
				
					//구분
					sendBuffer.position(sendBuffer.limit());
					sendBuffer.limit(sendBuffer.limit()+4);
					sendBuffer.put("OOOO".getBytes());
					
					//등록번호
					sendBuffer.position(sendBuffer.limit());
					sendBuffer.limit(sendBuffer.limit()+20);
					sendBuffer.put(txtArDrid.getText().getBytes());
					
					//등록처
					sendBuffer.position(sendBuffer.limit());
					sendBuffer.limit(sendBuffer.limit()+20);
					sendBuffer.put(txtArBranch.getText().getBytes());
					
					//금액
					sendBuffer.position(sendBuffer.limit());
					sendBuffer.limit(sendBuffer.limit()+20);
					sendBuffer.put(txtArAmount.getText().replaceAll(",", "").getBytes());
					
					//사유
					sendBuffer.position(sendBuffer.limit());
					sendBuffer.limit(sendBuffer.limit()+20);
					sendBuffer.put(txtArReason.getText().getBytes());
					
					//보내기
					//sendBuffer.position(sendBuffer.limit());
					//sendBuffer.limit(sendBuffer.limit()+1);
					//sendBuffer.put("$".getBytes());
					
					sendBuffer.limit(1024);
					sendBuffer.rewind();
					client.writeBuffer(sendBuffer);
					sendBuffer.clear();
					break;
				case 1:
					System.out.println("case 1 - 해지");
					if(tableSelectedRow == -1)
					{
						txtResult.setText("해지할 내역을 선택하십시오.");
						break;
					}
					if(!tblApryu.getValueAt(tableSelectedRow, 6).toString().isEmpty())
					{
						txtResult.setText("이미 해지된 압류  내역입니다.");
						tableSelectedRow = -1;
						break;
					}
					//tr		06
					sendBuffer.position(0);
					sendBuffer.limit(6);
					sendBuffer.put("20021S".getBytes());
					
					//계좌		11	6~17
					sendBuffer.position(sendBuffer.limit());
					sendBuffer.limit(sendBuffer.limit()+11);
					sendBuffer.put(txtAccNum.getText().replaceAll("-", "").getBytes());
				
					//구분
					sendBuffer.position(sendBuffer.limit());
					sendBuffer.limit(sendBuffer.limit()+4);
					sendBuffer.put("XXXX".getBytes());
					
					//ar_id
					sendBuffer.position(sendBuffer.limit());
					sendBuffer.limit(sendBuffer.limit()+4);
					sendBuffer.put(tblApryu.getValueAt(tableSelectedRow, 7).toString().getBytes());
					
					//등록처
					sendBuffer.position(sendBuffer.limit());
					sendBuffer.limit(sendBuffer.limit()+20);
					sendBuffer.put(txtArBranch.getText().getBytes());
					
					//보내기
					//sendBuffer.position(sendBuffer.limit());
					//sendBuffer.limit(sendBuffer.limit()+1);
					//sendBuffer.put("$".getBytes());
					
					sendBuffer.limit(1024);
					sendBuffer.rewind();
					client.writeBuffer(sendBuffer);
					sendBuffer.clear();
					tableSelectedRow = -1;
					txtArBranch.setText("");
					txtArReason.setText("");
					txtArDrid.setText("");
					txtArAmount.setValue(null);
					break;

				}
			}
		});
		btnOK.setBounds(619, 34, 65, 23);
		contentPane.add(btnOK);
		
		JSeparator separator = new JSeparator();
		separator.setBounds(12, 63, 817, 2);
		contentPane.add(separator);
		
		JLabel lblNewLabel_3 = new JLabel("압류등록처");
		lblNewLabel_3.setBounds(12, 75, 90, 15);
		contentPane.add(lblNewLabel_3);
		
		JLabel txtAr = new JLabel("압류등록사유");
		txtAr.setBounds(12, 125, 90, 15);
		contentPane.add(txtAr);
		
		JLabel lblNewLabel_6 = new JLabel("압류등록번호");
		lblNewLabel_6.setBounds(370, 75, 90, 15);
		contentPane.add(lblNewLabel_6);
		
		JLabel lblNewLabel_7 = new JLabel("압류금액");
		lblNewLabel_7.setBounds(12, 100, 90, 15);
		contentPane.add(lblNewLabel_7);
		
		txtArBranch = new JTextField();
		txtArBranch.setBounds(114, 72, 116, 21);
		contentPane.add(txtArBranch);
		txtArBranch.setColumns(10);
		
		txtArReason = new JTextField();
		txtArReason.setBounds(114, 122, 474, 21);
		contentPane.add(txtArReason);
		txtArReason.setColumns(10);
		
		txtArDrid = new JTextField();
		txtArDrid.setBounds(472, 72, 116, 21);
		contentPane.add(txtArDrid);
		txtArDrid.setColumns(10);
		
		txtArAmount = new JFormattedTextField(numberFormatter);
		txtArAmount.setBounds(114, 97, 116, 21);
		contentPane.add(txtArAmount);
		txtArAmount.setColumns(10);
		
		TableCellRenderer ren = new TableColor();
		
		try {
			tblApryu.setDefaultRenderer(Class.forName("java.lang.Object"), ren);
		} catch (ClassNotFoundException e) {
			e.printStackTrace();
		}
		
		
	}
	public void findAccountName()
	{
		if(txtAccNum.getText().length()==13)
		{
			String accountFindString = "2222ID";
			accountFindString+=String.format("%11s", txtAccNum.getText().replaceAll("-", ""));
			client.writeString(accountFindString+"$");
			System.out.println("계좌조회"+accountFindString);
			txtResult.setText("계좌조회");
		}
		else
		{
			txtResult.setText("계좌번호 11자리를 입력해 주세요.");	
		}
	}
	
	public void getApryuListByAccPW()
	{
		if(txtPassword.getPassword().length!=4)
		{
			if(txtAccNum.getText().length()!=11)
			{
				txtResult.setText("계좌번호11자리, 비밀번호4자리를 입력하여 주십시오.");
			}
			else
			{
				txtResult.setText("비밀번호 4자리를 바르게 입력하여 주십시오.");
			}
		}
		else
		{
			if(txtAccName.getText().isEmpty()) findAccountName();
			//System.out.println("질권 설정 내역 조회");
			// 압류 내역 조회.
			String accountFindString = "2222IW";
			accountFindString+=String.format("%11s%4s", txtAccNum.getText().replaceAll("-", ""), new String(txtPassword.getPassword()));
			client.writeString(accountFindString);//+"$");
			//System.out.println(accountFindString);
			txtResult.setText("");
		}
	}
	
	public void requestApryuList()
	{
		String sendString = "200299"+String.format("%11s", txtAccNum.getText().replaceAll("-", ""));
		client.writeString(sendString);
		
	}
	
	public class TableColor extends DefaultTableCellRenderer {

		public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int column) {

			Component cell = super.getTableCellRendererComponent(table, value, isSelected, hasFocus, row, column);

			// 가운데 정렬
			this.setHorizontalAlignment(JLabel.CENTER);

			// 색 삽입
			if (row%2==1) {
				cell.setBackground(new Color(195, 217, 235));
			} else {
				cell.setBackground(Color.WHITE);
			}

			return cell;

		}

	}
}
